// pages/zhongkao/zk_exam_registrationInfo/zk_exam_registrationInfo.js
const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    // 1. 基础信息
    base_candidate_info: {
      id_number: '',
      phone: '',
      name: '',
      gender: '',
      birth_date: '',
      ethnicity_id: '',
      foreign_language_id: '',
      political_status_id: ''
    },
    
    // 2. 中考报名信息
    zk_exam_info: {
      candidate_category_code: '',
      candidate_category_name: '',
      candidate_type_code: '',
      candidate_type_name: '',
      registration_site_code: '',
      registration_site_name: '',
      graduation_school_name: '',
      graduation_school_code: '',
      schooling_length: '',
      mailing_address: '',
      postal_code: '',
      special_skills: '',
      work_school_code: '',
      junior_position: ''
    },

    expanded: {
      base: false,
      exam: false
    },

    // 映射容器：存放 code->name
    idToName: {
      ethnicity: {},
      political: {},
      foreignlanguage: {},
      candidateCategory: {},
      candidateType: {},
      registrationSite: {},
      graduationSchool: {}
    }
  },

  async onLoad() {
    // 从本地读取基础信息和中考报名信息
    const B = wx.getStorageSync('base_candidate_info') || {};
    let Z = wx.getStorageSync('zk_exam_info') || {};
    
    // 本地不存在数据，从后端拉取
    if (JSON.stringify(Z) === '{}') {
      await tools.loadExamInfo(B.id_number);
      Z = wx.getStorageSync('zk_exam_info') || {};
    }

    // 格式化日期
    if (B.birth_date) B.birth_date = tools.formatDate(B.birth_date);

    this.setData({
      base_candidate_info: B,
      zk_exam_info: Z
    });
    
    // 获取映射名称
    await this.fetchNameMappings();
  },

  // 获取映射名称
  fetchNameMappings() {
    const { base_candidate_info: B, zk_exam_info: Z } = this.data;
    
    // 中考字段映射配置
    const zkMapCfg = [
      { key: 'ethnicity', field: 'ethnicity_id', url: id => `/ethnicity/info?id=${id}` },
      { key: 'political', field: 'political_status_id', url: id => `/politicalstatus/info?id=${id}` },
      { key: 'foreignlanguage', field: 'foreign_language_id', url: id => `/foreignlanguage/info?id=${id}` },
      { key: 'candidateCategory', field: 'candidate_category_code', url: code => `/zhongkao/category/selectByCode/${code}` },
      { key: 'candidateType', field: 'candidate_type_code', url: code => `/zhongkao/candidateType/selectByCode/${code}` },
      { key: 'registrationSite', field: 'registration_site_code', url: code => `/zhongkao/registrationSite/selectByCode/${code}` },
      { key: 'graduationSchool', field: 'graduation_school_code', url: code => `/zhongkao/graduationSchool/selectByCode/${code}` },
    ];

    const promises = [];
    
    zkMapCfg.forEach(({ key, field, url }) => {
      // 确定字段来源（基础信息或中考信息）
      const val = B[field] || Z[field];
      if (!val) return;
      
      promises.push(
        http.get(url(val)).then(res => {
          if (res.statusCode === 200) {
            const name = res.data?.data?.name || res.data?.name;
            if (name) {
              this.setData({
                [`idToName.${key}.${val}`]: name
              });
              console.log('')
            }
          }
        }).catch(err => {
          console.error(`获取${key}映射失败:`, err);
        })
      );
    });

    return Promise.all(promises).catch(console.error);
  },

  // 切换区块展开状态
  toggleSection(e) {
    const sec = e.currentTarget.dataset.section;
    this.setData({
      [`expanded.${sec}`]: !this.data.expanded[sec]
    });
  }
});